import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../../repositories/data_repository.dart';
import '../../../services/product_service.dart';
import '../../../services/device_service.dart';
import '../../../models/alert_log_model.dart';
import 'package:intl/intl.dart';

class AlertLogsController extends GetxController {
  // 数据仓库和缓存服务
  final DataRepository _dataRepository = Get.find<DataRepository>();
  final ProductService _productService = Get.find<ProductService>();
  final DeviceService _deviceService = Get.find<DeviceService>();
  
  // 告警日志列表数据
  final alertLogs = <AlertLog>[].obs;
  
  // 加载状态
  final isLoading = true.obs;
  final isLoadingMore = false.obs;
  
  // 分页信息
  final currentPage = 1.obs;
  final pageSize = 10.obs;
  final total = 0.obs;
  final hasMore = true.obs;
  
  // 过滤条件
  final deviceId = Rx<int?>(null);
  final productKey = Rx<String?>(null);
  final deviceSn = Rx<String?>(null);
  final alertName = Rx<String?>(null);
  final level = Rx<int?>(null);
  final status = Rx<int?>(null);
  final dateRange = Rx<DateTimeRange?>(null);
  
  // 日期格式化器
  final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
  
  @override
  void onInit() {
    super.onInit();
    // 初始化时预加载设备和产品数据，用于后续显示名称
    _preloadProductsAndDevices();
    loadAlertLogs();
  }
  
  // 预加载产品和设备数据以供后续使用
  Future<void> _preloadProductsAndDevices() async {
    try {
      // 加载产品和设备数据到缓存
      await _productService.getAllProducts();
      await _deviceService.getAllDevices();
    } catch (e) {
      debugPrint('预加载产品和设备数据失败: $e');
    }
  }
  
  // 加载告警日志列表
  Future<void> loadAlertLogs({bool refresh = true}) async {
    try {
      if (refresh) {
        isLoading.value = true;
        currentPage.value = 1;
        alertLogs.clear();
      } else {
        isLoadingMore.value = true;
      }
      
      String? beginTime;
      String? endTime;
      
      if (dateRange.value != null) {
        beginTime = _dateFormat.format(dateRange.value!.start);
        // 设置结束时间为当天23:59:59，确保包含当天数据
        final end = DateTime(
          dateRange.value!.end.year,
          dateRange.value!.end.month,
          dateRange.value!.end.day,
          23, 59, 59
        );
        endTime = _dateFormat.format(end);
      }
      
      final response = await _dataRepository.getAlertLogList(
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        deviceId: deviceId.value,
        productKey: productKey.value,
        deviceSn: deviceSn.value,
        alertName: alertName.value,
        level: level.value,
        status: status.value,
        beginTime: beginTime,
        endTime: endTime,
      );
      
      // 获取告警日志列表
      final logs = response.rows;
      
      // 补充设备和产品信息
      await _enrichAlertLogsWithDeviceAndProductInfo(logs);
      
      if (refresh) {
        alertLogs.assignAll(logs);
      } else {
        alertLogs.addAll(logs);
      }
      
      total.value = response.total;
      hasMore.value = alertLogs.length < total.value;
      
    } catch (e) {
      Get.snackbar(
        '加载失败',
        '获取告警日志列表失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    } finally {
      isLoading.value = false;
      isLoadingMore.value = false;
    }
  }
  
  // 为告警日志补充设备和产品信息
  Future<void> _enrichAlertLogsWithDeviceAndProductInfo(List<AlertLog> logs) async {
    for (int i = 0; i < logs.length; i++) {
      final log = logs[i];
      
      // 如果告警日志中已有设备名称和产品名称，则跳过
      if ((log.deviceName != null && log.deviceName != '') && 
          (log.productName != null && log.productName != '')) {
        continue;
      }
      
      // 从缓存中查找设备信息
      if (log.deviceId != null) {
        final device = await _deviceService.getDeviceById(log.deviceId!);
        if (device != null) {
          // 创建新的告警日志对象，添加设备名称
          logs[i] = log.copyWith(
            deviceName: device.deviceName ?? '未知设备',
            deviceSn: device.deviceSn ?? '未知设备编号'
          );
        }
      }
      
      // 从缓存中查找产品信息
      if (log.productId != null) {
        final product = await _productService.getProductById(log.productId!);
        if (product != null) {
          // 创建新的告警日志对象，添加产品名称
          logs[i] = logs[i].copyWith(
            productName: product.productName ?? '未知产品'
            // 不填充productKey，因为AlertLog类中的copyWith方法不支持这个参数
          );
        }
      }
    }
  }
  
  // 加载更多
  Future<void> loadMore() async {
    if (isLoadingMore.value || !hasMore.value) return;
    
    currentPage.value++;
    await loadAlertLogs(refresh: false);
  }
  
  // 刷新数据
  Future<void> refreshData() async {
    await loadAlertLogs();
  }
  
  // 确认告警
  Future<bool> confirmAlert(int logId) async {
    try {
      final success = await _dataRepository.confirmAlertLog(logId);
      if (success) {
        Get.snackbar(
          '成功',
          '告警已确认',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
        
        // 更新本地数据
        final index = alertLogs.indexWhere((log) => log.logId == logId);
        if (index != -1) {
          final updatedLog = alertLogs[index].copyWith(
            status: 2, // 更新状态为已确认
            confirmTime: _dateFormat.format(DateTime.now()),
            confirmUser: 'current_user', // 应从用户服务获取
          );
          
          alertLogs[index] = updatedLog;
          alertLogs.refresh();
        }
        
        return true;
      } else {
        Get.snackbar(
          '失败',
          '确认告警失败',
          snackPosition: SnackPosition.BOTTOM,
        );
        return false;
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '确认告警时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      return false;
    }
  }
  
  // 应用过滤器
  void applyFilters({
    int? deviceId,
    String? productKey,
    String? deviceSn,
    String? alertName,
    int? level,
    int? status,
    DateTimeRange? dateRange,
  }) {
    this.deviceId.value = deviceId;
    this.productKey.value = productKey;
    this.deviceSn.value = deviceSn;
    this.alertName.value = alertName;
    this.level.value = level;
    this.status.value = status;
    this.dateRange.value = dateRange;
    
    loadAlertLogs();
  }
  
  // 清除所有过滤条件
  void clearFilters() {
    deviceId.value = null;
    productKey.value = null;
    deviceSn.value = null;
    alertName.value = null;
    level.value = null;
    status.value = null;
    dateRange.value = null;
    
    loadAlertLogs();
  }
  
  // 获取告警级别对应的颜色
  Color getAlertLevelColor(int? level) {
    String colorCode = _dataRepository.getAlertLevelColor(level);
    return Color(int.parse(colorCode.substring(1, 7), radix: 16) + 0xFF000000);
  }
  
  // 获取告警状态对应的颜色
  Color getAlertStatusColor(int? status) {
    String colorCode = _dataRepository.getAlertStatusColor(status);
    return Color(int.parse(colorCode.substring(1, 7), radix: 16) + 0xFF000000);
  }
  
  // 根据设备ID获取设备名称
  Future<String> getDeviceNameById(int? deviceId) async {
    if (deviceId == null) return '未知设备';
    
    final device = await _deviceService.getDeviceById(deviceId);
    return device?.deviceName ?? '未知设备';
  }
  
  // 根据产品ID获取产品名称
  Future<String> getProductNameById(int? productId) async {
    if (productId == null) return '未知产品';
    
    final product = await _productService.getProductById(productId);
    return product?.productName ?? '未知产品';
  }
} 